package com.chice.scangundemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import android.widget.TextView;
import android.widget.Toast;

import com.chice.scangundemo.scangunpakage.ScanGun;
import com.chice.scangundemo.utils.ColorUtils;

//让扫码枪只能zaiactivity中响应而不再edittext中显示 只是加了
//android:inputType="number"
//android:digits="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"  限制只能输入数字  大小写子字母
//还有就是在Activity中拦截键盘是事件
public class MainActivity extends Activity {

    private ScanGun mScanGun = null;
    private TextView tvScanResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvScanResult = (TextView) findViewById(R.id.tvScanResult);

        // 设置key事件最大间隔，默认20ms，部分低端扫码枪效率低
        ScanGun.setMaxKeysInterval(50);
            mScanGun = new ScanGun(new ScanGun.ScanGunCallBack() {
            @Override
            public void onScanFinish(String scanResult) {
                Toast.makeText(MainActivity.this, "数据： "+scanResult, Toast.LENGTH_SHORT).show();
                tvScanResult.setText(scanResult);
                tvScanResult.setTextColor(ColorUtils.getRandomColorInt());

            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        mScanGun.isMaybeScanning(keyCode, event);
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 拦截物理键盘事件
        if (event.getKeyCode() > 6) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if(event.getKeyCode()==KeyEvent.KEYCODE_DEL){//将键盘的删除键传递下去
                    return super.dispatchKeyEvent(event);
                }
                this.onKeyDown(event.getKeyCode(), event);
            }
        }else{
            if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){//将键盘的返回事件传递下去
                return super.dispatchKeyEvent(event);
            }
        }
        return true;
    }

}
